import re
import time
import os
import requests
import pygame
import random
# 设置请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
}

# 定义基础 URL
url_base = 'https://dyllbk.xxtt.info/content/'
url_name = '22/emergency-project-ex-014-miki-w.html'  # 调整为你的具体 URL
#url_name = input("请输入'）：")
page = ''  # 初始页码设置为空

# 发送请求获取 HTML 代码
response = requests.get(url_base + url_name + page, headers=headers)
html = response.text
#print(response.text)

# 提取文件夹名称
dir_name = re.findall(r'<h3 style="font-style:normal;font-weight:400;" class="wp-block-post-title has-medium-font-size">(.*?)</h3>', html)[-1]
print(f"Folder Name: {dir_name}")  # 文件夹名字

# 提取照片数量
photos_num = re.findall(r'MB-(\d+)photos', html)
photos_num = int(photos_num[0]) if photos_num else 0
print(f"Total Photos: {photos_num}")  # 照片数量

# 创建文件夹
if not os.path.exists(dir_name):
    os.makedirs(dir_name)

# 下载每一页的照片
for page_num in range(1, (photos_num - 1) // 20 + 2):  # 计算需要下载的页数
    # 定义当前页面的 URL
    page_suffix = f"/{page_num}" if page_num > 1 else ""
    response = requests.get(url_base + url_name + page_suffix, headers=headers)
    html = response.text

    # 提取照片 URL
    urls = re.findall(r'src="(.*?)" width="1300" height="1500"', html)
    print(f"Downloading URLs from page {page_num}, found {len(urls)} URLs.")

    # 保存每一张照片
    for url in urls:
        #time.sleep(0.3)  # 延迟以防被限制

        random_sleep_time = random.uniform(0.5, 1.5)
        print(f"随机暂停时间: {random_sleep_time:.2f} 秒")
        time.sleep(random_sleep_time)
       # last_three_chars = file_name[-3:]  # 提取最后三位字符```
        f_name = url.split('.')[-2]
        file_name = f_name[-3:] + '.png'
        print('正在下载', file_name)
        response = requests.get(url)
        with open(dir_name + '/' + file_name, 'wb') as file:
            file.write(response.content)
print("所有照片下载完成！")
# 初始化pygame mixer
pygame.mixer.init()

# 加载音频文件
pygame.mixer.music.load('x.wav')

# 播放音频
pygame.mixer.music.play()

# 等待音乐播放结束
while pygame.mixer.music.get_busy():
    pygame.time.wait(100)